/*
 * @Author: yli
 * @Date: 2021-05-02 20:04:22
 * @LastEditors: yli
 * @LastEditTime: 2021-05-02 20:28:36
 * @Description: file content
 */

#include "key.h"

#include "main.h"
#include "stm32f4xx_ll_utils.h"
#include "stm32f4xx_ll_gpio.h"

#define KEY1_DOWN (LL_GPIO_IsInputPinSet(Key1_GPIO_Port, Key1_Pin))
#define KEY2_DOWN (LL_GPIO_IsInputPinSet(Key2_GPIO_Port, Key2_Pin))

/** 
 * Key1状态，初始未按下为: 
 * pressed: 0, pressed_nT: 0,
 * 处理完状态务必记得清零
 **/
KeyStatus Key1Status =
{ 0, 0 };

/** 
 * Key2状态，初始未按下为: 
 * pressed: 0, pressed_nT: 0, 
 * 处理完状态务必记得清零
 **/
KeyStatus Key2Status =
{ 0, 0 };

/**
 * 按键扫描
 * @description: 按键扫描
 * @param {uint8_t} key_type: 0, 拨码开关; 1， 轻触按键; key_type设为0时，mode参数失效
 * @param {uint8_t} mode: 0, 不支持连续按; 1， 支持连续按
 * @return {*}
 */
void KeyPressedScan(uint8_t key_type, uint8_t mode)
{
	static uint8_t key1_up = 1; // Key1 松开标志
	static uint8_t key2_up = 1; // Key2 松开标志
	if (mode || (!key_type))
	{
		key1_up = 1;
		key2_up = 1;
	}
	if (key1_up && KEY1_DOWN == 0)
	{
		LL_mDelay(5); // 去抖动
		key1_up = 0;
		if (KEY1_DOWN == 0)
		{
			Key1Status.pressed = 1;
			if (key_type)
			{
				Key1Status.pressed_nT += 1;
			}
			else
			{
				Key1Status.pressed_nT = 1;
			}
		}
	}
	if (key2_up && KEY2_DOWN == 0)
	{
		LL_mDelay(5); // 去抖动
		key2_up = 0;
		if (KEY2_DOWN == 0)
		{
			Key2Status.pressed = 1;
			if (key_type)
			{
				Key2Status.pressed_nT += 1;
			}
			else
			{
				Key2Status.pressed_nT = 1;
			}
		}
	}
}

void ClearKeyStatus(KeyStatus *key_status)
{
	key_status->pressed = 0;
	key_status->pressed_nT = 0;
}

uint8_t KeyPressing(Keyx key_x)
{
	switch (key_x) {
		case Key1:
			if(KEY1_DOWN == 0)
			{
				LL_mDelay(5);
				return (KEY1_DOWN == 0);
			}
			break;
		case Key2:
			if(KEY2_DOWN == 0)
			{
				LL_mDelay(5);
				return (KEY2_DOWN == 0);
			}
			break;
	}
	return 0;
}
